package com.itboye.sunsun.web.ui;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.sunsun.R;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.person.ui.NewsDetailShareFragment;
import com.itboye.sunsun.shop.ui.AllShopActivity;
import com.itboye.sunsun.support.BaseActivity;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.open.yyb.AppbarAgent;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

/**
 * 所有web页面 intent参数 title url </br> 安卓6.0模拟器可能会崩溃
 * 
 * @author Young
 * 
 */
public class WebActivity extends BaseActivity {

	TextView title;
	WebView webview;
	private static final String APP_ID = "wxa30658c4f4f6bbf4";
	NewsDetailShareFragment fragment;
	String url;
	private IWXAPI api;
	String imgUrl;
	private String content;// NewsDetail的新闻详情
	int shareType = 1;// 1：分享至朋友 2、分享之朋友圈
	Tencent mTencent;

	private final String APPID = "1105251111";

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_web);
		showProgressDialog("数据正在加载中，请稍后", true);
		// iwxapi = WXAPIFactory.createWXAPI(this,
		// "wxa30658c4f4f6bbf4");//wxa30658c4f4f6bbf4
		// iwxapi.registerApp("wxa30658c4f4f6bbf4");
		// title = (TextView) findViewById(R.id.title);
		// webview = (WebView) findViewById(R.id.webview);
		setStatusBarColor(R.color.orange);
		title.setText(getIntent().getStringExtra("title"));
		url = getIntent().getStringExtra("url");
		imgUrl = getIntent().getStringExtra("img");
		api = WXAPIFactory.createWXAPI(App.ctx, APP_ID);
		mTencent = Tencent.createInstance(APPID, this);
//		mTencent.startAppbar(this, AppbarAgent.TO_APPBAR_DETAIL);//要跳转至微社区（下载了应用宝的，未下载则不会）

		if (TextUtils.isEmpty(url)) {
			url = "http://baidu.com";
		}

		findViewById(R.id.backrela).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		webview.getSettings().setJavaScriptEnabled(true);
		webview.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				// TODO Auto-generated method stub
				super.onProgressChanged(view, newProgress);
				if (newProgress == 100) {
					try {

						closeProgressDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
				} else {

				}
			}
		});
		webview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view,
					String innerurl) {
				if (innerurl.contains("SUNSUN_SHARE_WECHAT")) {// 微信分享
					shareType = 1;
					beginShare(SendMessageToWX.Req.WXSceneSession);
					// shareToFriendOrFriends(SendMessageToWX.Req.WXSceneSession);
				} else if (innerurl.contains("SUNSUN_SHARE_CIRCLE")) {
					shareType = 2;
					beginShare(SendMessageToWX.Req.WXSceneSession);
					// shareToFriendOrFriends(SendMessageToWX.Req.WXSceneTimeline);
				} else if (innerurl.contains("SUNSUN_SHARE_QQ")) {
					shareToQQ();
				} else if (innerurl.contains("SUNSUN_GOTO_MART")) {
					Intent intent=new Intent(App.ctx,AllShopActivity.class);
					startActivity(intent);
				} else {
					// Toast.makeText(WebActivity.this, "3分享", 0).show();
					view.loadUrl(innerurl);
				}
				return true;
			}
		});

		webview.loadUrl(url);
	}

	// // 分享
	// public void shareToFriendOrFriends(int type) {
	// WXWebpageObject webpage0 = new WXWebpageObject();
	// webpage0.webpageUrl = url;
	// // 标题
	// WXMediaMessage msg0 = new WXMediaMessage(webpage0);
	// msg0.title = getIntent().getStringExtra("title2");
	// msg0.description = getIntent().getStringExtra("content");
	// // 商品图片
	// Bitmap thumb0 = BitmapFactory.decodeResource(getResources(),
	// R.drawable.ic_logo);
	// msg0.setThumbImage(thumb0);
	//
	// // 构建一个请求
	// SendMessageToWX.Req req0 = new SendMessageToWX.Req();
	// req0.message = msg0;
	// req0.scene = type;// WXSceneTimeline分享至朋友圈
	// req0.transaction = "sessionwebpage";
	// api.sendReq(req0);
	// }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (webview.canGoBack()) {
				webview.goBack();
				return true;
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	private void shareToQQ() {
		final Bundle params = new Bundle();
		params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE,
				QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
		params.putString(QQShare.SHARE_TO_QQ_TITLE,
				getIntent().getStringExtra("title2"));
		params.putString(QQShare.SHARE_TO_QQ_SUMMARY, getIntent()
				.getStringExtra("content"));
		if (url.contains("&from=app"))
			url = url.substring(0, url.length() - 9);
		params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
		System.out.println("分享出来的链接" + url);
		params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
		params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "森森休闲");
		// params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, "其他附加功能");
		mTencent.shareToQQ(this, params, new IUiListener() {

			@Override
			public void onError(UiError arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "分享失败，请重试", 0).show();
			}

			@Override
			public void onComplete(Object arg0) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "分享完成", 0).show();
			}

			@Override
			public void onCancel() {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "已取消", 0).show();
			}
		});

	}

	public void beginShare(int type) {
		new Thread(runnable).start();
	}

	Runnable runnable = new Runnable() {

		@Override
		public void run() {

			WXWebpageObject webpage0 = new WXWebpageObject();
			webpage0.webpageUrl = url;
			// 标题
			WXMediaMessage msg0 = new WXMediaMessage(webpage0);
			msg0.title = getIntent().getStringExtra("title2");
			msg0.description = getIntent().getStringExtra("content");
			// 商品图片
			Bitmap thumb0 = null;
			if (imgUrl != null) {
				thumb0 = Bitmap.createScaledBitmap(GetLocalOrNetBitmap(imgUrl),
						120, 120, true);// 压缩Bitmap
				thumb0 = compressImage(thumb0);
			} else {
				thumb0 = BitmapFactory.decodeResource(getResources(),
						R.drawable.defaultimage);
			}
			msg0.setThumbImage(thumb0);

			// 构建一个请求
			SendMessageToWX.Req req0 = new SendMessageToWX.Req();
			req0.message = msg0;
			if (shareType == 1) {
				req0.scene = SendMessageToWX.Req.WXSceneSession;// W
			} else {
				req0.scene = SendMessageToWX.Req.WXSceneTimeline;// SceneTimeline分享至朋友圈
			}
			req0.transaction = "sessionwebpage";
			api.sendReq(req0);

		}
	};

	private Bitmap getBitmap(String imgUrl) {
		URL myFileUrl = null;

		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(imgUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {

			HttpURLConnection conn = (HttpURLConnection) myFileUrl

			.openConnection();
			conn.setDoInput(true);
			conn.connect();

			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {

			e.printStackTrace();
		}
		return createBitmapThumbnail(bitmap);
	}

	public Bitmap createBitmapThumbnail(Bitmap bitMap) {
		int width = bitMap.getWidth();
		int height = bitMap.getHeight();
		// 设置想要的大小
		int newWidth = 99;
		int newHeight = 99;
		// 计算缩放比例
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 取得想要缩放的matrix参数
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// 得到新的图片
		Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height,
				matrix, true);
		return newBitMap;
	}

	private Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 90, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 63) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	/**
	 * 把网络资源图片转化成bitmap
	 * 
	 * @param url
	 *            网络资源图片
	 * @return Bitmap
	 */
	public static Bitmap GetLocalOrNetBitmap(String url) {
		Bitmap bitmap = null;
		InputStream in = null;
		BufferedOutputStream out = null;
		try {
			in = new BufferedInputStream(new URL(url).openStream(), 1024);
			final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
			out = new BufferedOutputStream(dataStream, 1024);
			copy(in, out);
			out.flush();
			byte[] data = dataStream.toByteArray();
			bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
			data = null;
			return bitmap;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static void copy(InputStream in, OutputStream out)
			throws IOException {
		byte[] b = new byte[1024];
		int read;
		while ((read = in.read(b)) != -1) {
			out.write(b, 0, read);
		}
	}

}
